<?php
namespace app\common\event;
use app\common\model\UrmWelcomeMsg as UrmWelcomeMsgModel;
use XYCms\WorkWeChat as XYCmsWorkWeChat;

/**
 * 定时刷新素材管理任务
 * @Class RefreshTemporaryMedia
 * @Author: hhm <huanghemao@xycms.com>
 * @DateTime: 2022/3/21 0021 下午 14:25
 * @package app\common\event
 */
class RefreshTemporaryMedia
{

    public function run()
    {
        $welcome=UrmWelcomeMsgModel::where('type',2)->where('content_type',3)->select();
        if ($welcome){
            $api = new XYCmsWorkWeChat();
            foreach ($welcome as $v){
                $itemData=json_decode($v->item_data,true);
                $msgData=[
                    'template_id'=>$v->template_id,
                    "text"=>[
                        "content"=>$v->content
                    ],
                    'miniprogram'=>[
                        'title'=>$itemData['title'],
                        'appid'=>$itemData['appid'],
                        'page'=>$itemData['page'],
                        'pic_media_id'=>$this->uploadMediaToWechat($itemData['path'],$api)
                    ]
                ];
                $ret=$api->editGroupWelcomeTemplate($msgData);
                if ($ret['errcode'] == 90208){
                    echo "小程序appid不匹配，请确认小程序关联到企业的小程序应用:{$welcome->template_id}" ;
                    return false;
                }
            }
        }
        return true;
    }

    private function uploadMediaToWechat($saveFile,$api){
        $res = $api->uploadMedia(public_path() . $saveFile);
        return $res['media_id'];
    }
}